class BoardController < BaseController
  
  #【参数】
  #【返回值】
  #【注意】
  #【作者】 by ljl 2012.08.24
  def item
    if params[:id].blank? || !@board = Board.find_by_id(params[:id])
      raise ActionController::UnknownAction
    else
      if @board.blank?
        render :template => "/pin/error"
      else
        @user = @board.user
      end
    end
  end
  
  #【参数】
  #【返回值】
  #【注意】
  #【作者】 by ljl 2012.08.22
  def create
    user = User.find_by_id(session[:user])
    if user.blank?
      r = {:status => "error"}
    else
      board = Board.create({:name => params[:name], :user_id => user.id})
      r = {:status => "success", 
           :name => board.name, 
           :id => board.id
      }
    end
    render :json => r.to_json 
  end
  
  #【参数】
  #【返回值】
  #【注意】
  #【作者】 by ljl 2012.08.27
  def edit
    @board = Board.find_by_id(params[:id])
    if @board.blank?
      render :template => "/board/error"
    else
      return unless request.post?
      begin
        @board.attributes = params[:board]
        @board.save!
        redirect_to :controller => :board, :action => :item, :id => @board.id
      rescue ActiveRecord::RecordInvalid
        render :action => :edit
      end
    end
  end
  
  #【参数】
  #【返回值】
  #【注意】
  #【作者】 by ljl 2012.08.27
  def load_data
    json = []
    board = Board.find_by_id(params[:board_id])
    pins = Pin.find(:all, 
                    :order => "created_at desc, id desc", 
                    :conditions => ["board_id = ?", board.id],
                    :limit => APP_CONFIG[:page][:home_page], 
                    :offset => (params[:page].to_i - 1) * APP_CONFIG[:page][:home_page]
    )
    pins.each do |pin|
      user = pin.user
      user_pin = UserPin.find_by_user_id_and_pin_id(session[:user], pin.id)
      p = {:id => pin.id,
           :board_id => pin.board.id,
           :board_title => pin.board.name,
           :user => {:id => user.id,
                     :name => user.name},
           :user_id => user.id,
           :media => pin.media,
           :description => pin.description,
           :link_count => pin.user_pins.count,
           :comment_count => pin.comments.count,
           :is_like  => true,
           :like_action => "",
           :like_btn => ""
      }
      if logged_in?
          p[:is_like] = current_user.id == user.id ? false : true 
        end
      if user_pin.present?
        p[:like_btn] = user_pin.like ? "取消喜欢" : "<em></em>喜欢"
        p[:like_action] = "unlike"
      else
        p[:like_btn] = "<em></em>喜欢"
        p[:like_action] = "like"
      end
      json << p
    end
    render :json => json.to_json
  end
  
end
